package com.ljb.commlibrary.permission;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import java.util.List;

/**
 * 权限申请的工具类
 * Created by ljb on 2018/5/2.
 */

public class PermissionUtils implements DefaultPermissionSetting.PermissionSettingListener {
    private static final String TAG = "PermissionUtils";

    private Activity mActivity;
    private DefaultPermissionSetting mSetting;
    private PermissionCallBack mCallback;

    public PermissionUtils(Activity activity) {
        if (activity == null) {
            throw new IllegalArgumentException("PermissionUtils: activity不能为空");
        }
        mActivity = activity;
        if (mSetting == null)
            mSetting = new DefaultPermissionSetting(mActivity, this);
    }

    /**
     * 申请权限
     *
     * @param permissions
     * @return
     */
    public void request(String... permissions) {
        AndPermission.with(mActivity)
                .permission(permissions)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Log.e(TAG, "权限成功: " + TextUtils.join(",", permissions));

                        //获取到权限
                        if (mCallback != null)
                            mCallback.onPermissionSucess(permissions);
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        Log.e(TAG, "权限失败: " + TextUtils.join(",", permissions));
//                        //获取权限失败

                        if (AndPermission.hasAlwaysDeniedPermission(mActivity, permissions)) {
                            mSetting.showSetting(permissions);
                        } else {
                            if (mCallback != null)
                                mCallback.onPermissionFaild(permissions);
                        }
                    }
                })
                .start();
    }

    /**
     * 设置回调,需要放在request()方法之前
     *
     * @param permissionCallBack
     * @return
     */
    public PermissionUtils setCallback(PermissionCallBack permissionCallBack) {
        mCallback = permissionCallBack;
        return this;
    }

    @Override
    public void onSettingCancleClick(List<String> permissions) {
        Log.e(TAG, "onSettingCancleClick: ");
        if (mCallback != null)
            mCallback.onPermissionSettingCancle(permissions);
    }

}
